package com.xbongbong.paas.lowcode.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.factory.LowCodeHandlerFieldFactory;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.abstracts.AbstractLowCodeHandlerFieldService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.pro.department.pojo.DepartmentUserPojo;
import com.xbongbong.pro.lowcodeexecute.pojo.LowCodeExecuteServicePojo;
import com.xbongbong.sys.domain.entity.DepartmentEntity;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author 吴峰
 * @date 2021/03/18 15:08
 */
@Service("lowCodeHandlerDepartmentGroupServiceImpl")
public class LowCodeHandlerDepartmentGroupServiceImpl extends AbstractLowCodeHandlerFieldService {
    @PostConstruct
    public void register() {
        LowCodeHandlerFieldFactory.LOW_CODE_HANDLER_FIELD.put(FieldTypeEnum.DEPT_GROUP.getType(), this);
    }

    @Override
    public Object handlerField(FieldAttrEntity fieldAttrEntity, JSONObject data, LowCodeExecuteServicePojo lowCodeExecuteServicePojo) throws XbbException {
        List<Long> departmentIdList = JSON.parseArray(JSON.toJSONString(data.get(fieldAttrEntity.getAttr())), Long.class);
        if (Objects.isNull(departmentIdList)) {
            return null;
        }
        List<DepartmentUserPojo> departmentUserPojoList = new ArrayList<>();
        departmentIdList.forEach(item->{
            Map<String, DepartmentEntity> departmentMap = lowCodeExecuteServicePojo.getUserAndDepartmentGetVO().getDepartmentMap();
            DepartmentUserPojo departmentUserPojo = new DepartmentUserPojo();
            departmentUserPojo.setId(item);
            DepartmentEntity departmentEntity = departmentMap.get(item);
            if (Objects.nonNull(departmentEntity)) {
                departmentUserPojo.setName(departmentEntity.getName());
            }
            departmentUserPojoList.add(departmentUserPojo);
        });

        return departmentUserPojoList;
    }
}
